import React, {useState, useEffect, useRef, useContext} from 'react'
import axios from 'axios'
import {Table, Button, Modal, Input, Form} from 'antd'
import {DeleteOutlined,ExclamationCircleOutlined } from '@ant-design/icons'
const { confirm } = Modal;

export default function NewsCategory() {
    const [category, setCategory] = useState([])
    useEffect(() => {
        axios.get('/categories').then(res=>{
            let list = res.data;
            list.forEach(item => {
                if(item.children?.length===0)
                    item.children="";
            });
            setCategory(list);
        })
    }, [])
    const handleSave = (record) => {
        setCategory(category.map(item=>{
            if(item.id===record.id){
                return {
                    id:item.id,
                    title:record.title,
                    value:record.title
                }
            }
            return item
        }))
        axios.patch(`/categories/${record.id}`,{
            title:record.title,
            value:record.value
        })
    }
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
            render(id) {
                return <b>{id}</b>
            },
        },
        {
            title: '新闻标题',
            dataIndex: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '新闻标题',
                handleSave: handleSave,
            })
        },
        {
            title:'操作',
            render(item){
                return <div>
                    <Button shape="circle" type="primary" danger icon={<DeleteOutlined/>} onClick={()=>comfirmDelete(item)} ></Button>
                </div>
            }
        }
    ];

    const comfirmDelete=(item)=>{
        confirm({
            title: '确认',
            icon: <ExclamationCircleOutlined />,
            content: '是否删除改权限？',
            okText: '是',
            okType: 'danger',
            cancelText: '否',
            onOk() {
                if(item.grade===1){
                    const newList =category.filter(data=>data.id!==item.id);
                    setCategory(newList);
                    axios.delete(`/rights/${item.id}`).then(res=>{
                    })
                }else{
                    const upItem = category.filter(data=>data.id===item.rightId)   //找到二级权限的上一级
                    upItem[0].children =upItem[0].children.filter(data=>data.id!==item.id);
                    //重新赋值，因为filter只能复制一层，使用这里是直接修改内存里的right表
                    setCategory([...category])//为了重新渲染，用新数组
                    axios.delete(`/children/${item.id}`);
                }
            },
            onCancel() {},
        });
    }
    const EditableContext = React.createContext(null);
    //上下文对象
    const EditableRow = ({ index, ...props }) => {
        const [form] = Form.useForm();
        return (
            <Form form={form} component={false}>
                <EditableContext.Provider value={form}>
                    <tr {...props} />
                </EditableContext.Provider>
            </Form>
        );
    };
    const EditableCell = ({title, editable, children, dataIndex, record,handleSave, ...restProps
                           }) => {
        const [editing, setEditing] = useState(false);
        const inputRef = useRef(null);
        const form = useContext(EditableContext);//使用上下文对象
//TODO:  hooks  上下文
        useEffect(() => {
            if (editing) {
                inputRef.current.focus();
            }
        }, [editing]);

        const toggleEdit = () => {
            setEditing(!editing);
            form.setFieldsValue({
                [dataIndex]: record[dataIndex],
            });
        };

        const save = async () => {
            try {
                const values = await form.validateFields();
                toggleEdit();
                handleSave({ ...record, ...values });
            } catch (errInfo) {
                console.log('Save failed:', errInfo);
            }
        };

        let childNode = children;

        if (editable) {
            childNode = editing ? (
                <Form.Item
                    style={{
                        margin: 0,
                    }}
                    name={dataIndex}
                    rules={[
                        {
                            required: true,
                            message: `${title} is required.`,
                        },
                    ]}
                >
                    <Input ref={inputRef} onPressEnter={save} onBlur={save} />
                </Form.Item>
            ) : (
                <div
                    className="editable-cell-value-wrap"
                    style={{
                        paddingRight: 24,
                    }}
                    onClick={toggleEdit}
                >
                    {children}
                </div>
            );
        }

        return <td {...restProps}>{childNode}</td>;
    };

    return (
        <div>
            <Table dataSource={category} columns={columns} pagination={{pageSize:10}} rowKey={item=>item.id}
                   components={{
                       body: {
                           row: EditableRow,
                           cell: EditableCell,
                       }
                   }}
            />
        </div>
    )
}
